import { create } from 'zustand';
import { Toast } from 'antd-mobile';
import axiosInstance from '../api/axios';
import { endpoints } from '../api/endpoints';
import usePointsStore from './pointsStore';
import { decryptAndParse } from '../utils/aesDecryptor';


const usePlayVideoStore = create((set, get) => ({
  // 视频播放列表
  playlist: [],
  // 当前播放的视频索引
  currentIndex: 0,
  // 加载状态
  isLoading: false,
  // 是否已经没有更多视频
  noMoreVideos: false,
  isFirstLoad: true, // Flag to skip reporting on first load
  
  // 获取当前播放视频
  getCurrentVideo: () => {
    const { playlist, currentIndex } = get();
    return playlist.length > 0 ? playlist[currentIndex] : null;
  },
  
  // 是否是第一个视频
  isFirstVideo: () => get().currentIndex === 0,
  
  // 是否是最后一个视频
  isLastVideo: () => get().currentIndex === get().playlist.length - 1,
  
  // 初始化加载播放列表
  initPlaylist: async () => {
    const canReportPoints = await usePointsStore.getState().canEarnPoints;
    if (!get().isFirstLoad && canReportPoints) {
      await usePointsStore.getState().reportPoints(); 
    }
    
    set({ isLoading: true });
    
    try {
      const response = await axiosInstance.post(endpoints.getVideoPlaylist);
      const encryptedData = response.data?.data;
      
      if (encryptedData && typeof encryptedData === 'string') {
        // 解密加密数据
        let decryptedData;
        try {
          decryptedData = await decryptAndParse(encryptedData);
          console.log('视频数据解密成功:', decryptedData);
        } catch (decryptError) {
          console.error('视频数据解密失败，尝试直接使用原始数据:', decryptError);
          // 如果解密失败，尝试直接使用原始数据（向后兼容）
          decryptedData = encryptedData;
        }

        // 处理解密后的数据
        let videoData;
        if (typeof decryptedData === 'string') {
          // 如果解密后仍然是字符串，尝试解析JSON
          try {
            videoData = JSON.parse(decryptedData);
          } catch (parseError) {
            console.error('解密数据JSON解析失败:', parseError);
            videoData = decryptedData;
          }
        } else {
          videoData = decryptedData;
        }

        // 兼容字符串数组和对象数组
        const normalizedPlaylist = Array.isArray(videoData) ? videoData.map(item =>
          typeof item === 'string' ? { url: item } : item
        ) : [];

        usePointsStore.getState().setSecurity(response.data.security);
        usePointsStore.getState().setTimestamp(response.data.timestamp);

        set({ 
          playlist: normalizedPlaylist,
          currentIndex: 0,
          isLoading: false,
          noMoreVideos: normalizedPlaylist.length === 0,
          isFirstLoad: false, // Subsequent loads are not the first
        });
      } else if (Array.isArray(encryptedData)) {
        // 如果数据已经是数组（未加密的情况），直接使用
        const normalizedPlaylist = encryptedData.map(item =>
          typeof item === 'string' ? { url: item } : item
        );

        usePointsStore.getState().setSecurity(response.data.security);
        usePointsStore.getState().setTimestamp(response.data.timestamp);

        set({ 
          playlist: normalizedPlaylist,
          currentIndex: 0,
          isLoading: false,
          noMoreVideos: normalizedPlaylist.length === 0,
          isFirstLoad: false,
        });
      } else {
        console.error("Unexpected playlist response structure:", encryptedData);
        set({ playlist: [], currentIndex: 0, isLoading: false, noMoreVideos: true });
      }
    } catch (error) {
      console.error('获取播放列表失败:', error);
      set({ isLoading: false, noMoreVideos: true });
    }
  },
  
  // 播放上一个视频
  playPrevious: () => {
    const { currentIndex } = get();
    if (currentIndex > 0) {
      set(state => ({ currentIndex: state.currentIndex - 1 }));
    }
  },
  
  // 播放下一个视频
  playNext: async () => {
    const { currentIndex, playlist, initPlaylist, isLastVideo } = get();
    
    if (isLastVideo()) {
      // Reached the end, load a new playlist, which will also trigger reporting.
      Toast.show({ content: '加载更多..', position: 'bottom' });
      await initPlaylist();
    } else if (currentIndex < playlist.length - 1) {
      set(state => ({ currentIndex: state.currentIndex + 1 }));
    }
  },
  
  // 重置状态
  resetState: () => {
    set({
      playlist: [],
      currentIndex: 0,
      isLoading: false,
      noMoreVideos: false,
      isFirstLoad: true, // Reset the flag
    });
  }
}));

export default usePlayVideoStore;
